// miniprogram/pages/foundearnings.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
import QR from '../../miniprogram_npm/qrcode-base64/index.js'
import { http, jsonpToJson, env } from '../../utils/index.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    times: 0,
    fundId: '',
    fundCode: '',
    fundQuotient: '',
    editReadOnly: false,
    earnings: 0,
    datas: [],
    groups: [],
    sort: '',
    sortValue: '',

    fundActionsheetVisible: false,
    actionsGroup: [
      { text: '查看详情', value: 'detail' },
      { text: '编辑', value: 'edit' },
      { text: '加减仓', value: 'editQuotient' },
      { text: '删除', value: 'delete' }
    ],

    // ----------------
    result: "0",
    id1: "clear",
    id2: "back",
    id3: "time",
    id4: "div",
    id5: "mul",
    id6: "sub",
    id7: "add",
    id8: "dot",
    id9: "eql",
    id10: "num_0",
    id11: "num_1",
    id12: "num_2",
    id13: "num_3",
    id14: "num_4",
    id15: "num_5",
    id16: "num_6",
    id17: "num_7",
    id18: "num_8",
    id19: "num_9",
    buttonDot: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let isProductionEnv = await env()
    this.setData({
      show: true,
      isProductionEnv,
      showNotification: true
    })

    setTimeout(() => {
      this.setData({
        showNotification: false
      })
    }, 3000)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.isImagePreview) {
      this.isImagePreview = false
      return
    }
    this.getData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getData()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  async showWechatGroup () {
    return
    // let { result } = await wx.cloud.callFunction({
    //   name: 'getWechatGroup'
    // })
    // let groups = result.data
    // groups.forEach(group => {
    //   let src = QR.drawImg(group.url, {
    //     typeNumber: 4,
    //     errorCorrectLevel: 'M',
    //     size: 500
    //   })
    //   group.src = src
    // })
    // this.setData({
    //   groups,
    //   wechatGroupShow: true
    // })
  },
  groupCodePreview (e) {
    this.isImagePreview = true
    let src = e.currentTarget.dataset.src
    wx.previewImage({
      urls: [src],
    })
  },
  wechatGroupConfirm () {
    this.setData({
      wechatGroupShow: false
    })
  },
  saveCodeToLocal (e) {
    let imgSrc = e.currentTarget.dataset.src
    var magager = wx.getFileSystemManager()
    magager.writeFile({
      filePath: wx.env.USER_DATA_PATH + '/code.png',
      data: imgSrc.slice(22),
      encoding: 'base64',
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: wx.env.USER_DATA_PATH + '/code.png',
          success: function (res) {
            wx.showToast({
              title: '图片保存成功',
            })
          },
          fail: function (err) {
            console.log(err)
          }
        })
      }, fail: err => {
        console.log(err)
      }
    })
  },
  showAddFund () {
    this.setData({
      addFundShow: true,
      editReadOnly: false,
      fundCode: '',
      fundQuotient: '',
    })
  },
  onFundChange (event) {
    this.setData({
      [event.currentTarget.dataset.id]: event.detail
    })
  },
  async zixuan () {
    let { result } = await wx.cloud.callFunction({
      name: 'getMyFund'
    })
    let zixuanjijins = result.data || []
    // 并存入缓存
    wx.setStorage({ key: 'zixuanjijins', data: zixuanjijins })

    return zixuanjijins
  },
  getUpdateFund (codes) {
    return new Promise(resolve => {
      let promises = []
      codes.forEach(code => {
        let prmoise = http({
          url: `https://fundgz.1234567.com.cn/js/${code}.js`,
          method: 'get',
          loading: false
        })
        promises.push(prmoise)
      })
      Promise.all(promises).then(res => {
        let obj = {}
        res.forEach(fund => {
          if (fund) {
            fund = jsonpToJson(fund)
            obj[fund.fundcode] = fund
          }
        })

        resolve(obj)
      })
    })
  },
  async fmtData (data = []) {
    if (!data.length) {
      return data
    }
    let result = []
    let codes = data.filter(item => typeof item.code !== 'undefined').map(item => item.code).join(',')

    let jjInfos = await http({
      url: `https://fundmobapi.eastmoney.com/FundMNewApi/FundMNFInfo?pageIndex=1&pageSize=50&plat=Android&appType=ttjj&product=EFund&Version=1&deviceid=ssdfsdfsdf&Fcodes=${codes}`,
      method: 'get',
      loading: false
    })

    let jjDatas = jjInfos.Datas
    let jjExpansion = jjInfos['Expansion']

    let jjDatasObject = {}
    let updateCodes = []

    jjDatas.forEach(item => {
      jjDatasObject[item.FCODE] = item
      if (item.PDATE == jjExpansion.GZTIME) {
        updateCodes.push(item.FCODE) // 记录已更新数据
      }
    })

    let updatedFunds = await this.getUpdateFund(updateCodes)

    for (let item of data) {
      if (!item.code) {
        continue
      }

      let jjData = jjDatasObject[item.code] || {}

      let isUpdate = jjData.PDATE == jjExpansion.GZTIME
      let yesterday_jingzhi = jjData.NAV // 昨天的净值
      let current_jingzhi = jjData.GSZ // 当前估值
      let zzl = jjData.GSZZL // 增长率

      if (isUpdate) {
        // 说明更新了
        // 通过接口请求昨天的净值
        let fund = updatedFunds[item.code] || {}
        yesterday_jingzhi = fund.dwjz // fundmoba接口的净值已更新为今天，取fundgz接口的昨天净值
        current_jingzhi = jjData.NAV // 当前估值更新为实际净值
        zzl = Number((current_jingzhi - yesterday_jingzhi) / yesterday_jingzhi * 100).toFixed(2)
      }

      let earning = Number((current_jingzhi - yesterday_jingzhi) * item.quotient).toFixed(2) // 收益

      result.push({
        ...item,
        name: jjData.SHORTNAME,
        code: jjData.FCODE || item.code,
        gsz: current_jingzhi,
        gszzl: isNaN(zzl) ? '--' : zzl,
        earning: isNaN(earning) ? '--' : earning,
        isUpdate: isUpdate && !isNaN(earning)
      })
    }

    if (this.data.sort && this.data.sortValue) {
      let sortKey = this.data.sort

      let data = result.filter(item => item[sortKey] != '--') || []
      let noData = result.filter(item => item[sortKey] == '--') || []

      if (this.data.sortValue == 'asc') {
        data = data.sort((a, b) => a[sortKey] - b[sortKey])
      } else if (this.data.sortValue == 'desc') {
        data = data.sort((a, b) => b[sortKey] - a[sortKey])
      }

      data.push(...noData)
      result = data
    }

    this.setData({
      datas: result
    })

    return result
  },
  async fmtData1 (data = []) {
    let result = []
    for (let item of data) {
      if (!item.code) {
        continue
      }

      let res = await http({
        url: `https://fundgz.1234567.com.cn/js/${item.code}.js`,
        method: 'get',
        loading: false
      })

      if (res) {
        res = jsonpToJson(res)
      }
      let earning = Number((res.gsz - res.dwjz) * item.quotient).toFixed(2)

      result.push({
        ...item,
        name: res.name,
        code: res.fundcode || item.code,
        gsz: res.gsz || 0,
        gszzl: res.gszzl || 0,
        earning: isNaN(earning) ? 0.00 : earning
      })
      this.setData({
        datas: result
      })
    }

    return result
  },
  async getData (refresh = false) {
    wx.showLoading({ title: "加载中..." })
    // 先检查本地是否有缓存
    let zixuanjijins = wx.getStorageSync('zixuanjijins')
    if (!zixuanjijins || refresh) {
      // 若没有则 从数据库查询
      zixuanjijins = await this.zixuan()
    }

    // 调试模式
    // let { result } = await wx.cloud.callFunction({
    //   name: 'getUserFund',
    //   data: {
    //     OPENID: 'oCrx85JL5ObHLF1rejP54n6FF3zY'
    //   }
    // })
    // let zixuanjijins = result.data
    // 调试模式

    this.setData({
      datas: []
    })
    await this.fmtData(zixuanjijins)

    // 计算盈亏估算
    let earnings = 0
    this.data.datas.forEach(item => {
      let earning = Number(item.earning)
      if (!isNaN(earning)) {
        earnings += earning
      }
    })
    this.setData({
      earnings: Number(earnings).toFixed(2)
    })
    wx.hideLoading()
  },
  async addFundConfirm () {
    if (!this.data.fundCode || !this.data.fundQuotient) {
      // 反之提示
      Toast.fail({ zIndex: 99999, message: '请输入基金编码及份额' })
      return
    }

    if (isNaN(Number(this.data.fundQuotient))) {
      Toast.fail({ zIndex: 99999, message: '份额请输入数字' })
      return
    }

    // 先检查是否已存在
    let isExist = this.data.datas.find(item => item.code == this.data.fundCode)
    if (isExist) {
      Toast.fail({ zIndex: 99999, message: '该基金已添加' })
      return
    }

    // 检查基金是否正确
    http({
      url: `https://fundgz.1234567.com.cn/js/${this.data.fundCode}.js`,
      method: 'get',
      errorDialog: false
    }).then(async res => {
      // 正确的基金
      // 执行添加
      let { result } = await wx.cloud.callFunction({
        name: 'addMyFund',
        data: {
          fundCode: this.data.fundCode,
          fundQuotient: this.data.fundQuotient
        }
      })

      if (result.error) {
        Toast.fail({ zIndex: 99999, message: result.error })
        return
      }
      Toast.success({ message: '操作成功' })
      // 添加成功，刷新数据
      this.setData({
        addFundShow: false
      })
      this.getData(true)
    }, res => {
      // 404
      Toast.fail({ zIndex: 99999, message: '找不到该基金，请输入正确的基金编码' })
    })

  },
  async editFundConfirm () {
    if (!this.data.fundCode) {
      // 反之提示
      Toast.fail({ zIndex: 99999, message: '请输入基金份额' })
      return
    }

    // 执行修改
    let { result } = await wx.cloud.callFunction({
      name: 'editMyFund',
      data: {
        fundQuotient: this.data.fundQuotient,
        fundId: this.data.fundId
      }
    })

    if (result.error) {
      Toast.fail({ zIndex: 99999, message: result.error })
      return
    }
    Toast.success({ message: '操作成功' })
    // 添加成功，刷新数据
    this.setData({
      addFundShow: false
    })
    this.getData(true)

  },
  async deleteFundConfirm (e) {
    this.setData({
      deleteShow: false
    })
    if (e.detail.index == 0) {
      // 取消
      return
    }

    await wx.cloud.callFunction({
      name: 'deleteMyFund',
      data: {
        fundQuotient: this.data.fundQuotient,
        fundId: this.data.fundId
      }
    })

    Toast.success({ message: '操作成功' })
    this.getData(true)
  },
  showDeleteFund (e) {
    let fundId = e.currentTarget.dataset.id
    this.setData({
      addFundShow: false,
      deleteShow: true,
      fundId
    })
  },
  showEditFund (e) {
    let item = e.currentTarget.dataset.item
    this.setData({
      addFundShow: true,
      editReadOnly: true,
      fundId: item._id,
      fundCode: item.code,
      fundName: item.name,
      fundQuotient: item.quotient,
    })
  },
  getNextSortValue () {
    if (this.data.sortValue == '') {
      // 先倒叙
      return 'desc'
    }

    if (this.data.sortValue == 'desc') {
      // 顺序
      return 'asc'
    }

    if (this.data.sortValue == 'asc') {
      // 清空排序
      return ''
    }
  },
  sortData (e) {
    let key = e.currentTarget.dataset.key
    let sortValue = ''
    if (!this.lastSort || this.lastSort !== key) {
      // 首次排序
      this.setData({
        sort: key
      })
      sortValue = 'desc'
    } else {
      sortValue = this.getNextSortValue()
    }

    if (!sortValue) {
      // 清空
      this.setData({
        sort: ''
      })
      this.lastSort = ''
    } else {
      this.lastSort = key
    }
    this.data.sortValue = sortValue
    // 刷新数据
    this.getData()
  },
  showActionSheet (e) {
    this.selectedFund = e.currentTarget.dataset.item
    this.setData({
      fundActionsheetVisible: true
    })
  },
  handleActionClick (e) {
    let type = e.detail.value
    this.setData({
      fundActionsheetVisible: false
    })
    switch (type) {
      case 'detail':
        wx.navigateTo({
          url: `../fundDetail/fundDetail?code=${this.selectedFund.code}`
        })
        break;
      case 'edit':
        wx.navigateTo({
          url: `../fundEdit/fundEdit?code=${this.selectedFund.code}&quotient=${this.selectedFund.quotient}$cost=${this.selectedFund.cost}`
        })
        break
      default:
        break;
    }
  },
  // -------------------
  clickButton: function (e) {
    var buttonVal = e.target.id
    var res = this.data.result
    var newbuttonDot = this.data.buttonDot
    var sign
    if (buttonVal >= "num_0" && buttonVal <= "num_9") {
      var num = buttonVal.split('_')[1]
      if (res == "0" || res.charAt(res.length - (length - 1)) == "=") {
        res = num
      }
      else {
        res = res + num
      }
    }
    else {
      if (buttonVal == "dot") {
        if (!newbuttonDot) {
          res = res + '.'
        }
      }
      else if (buttonVal == "clear") {
        res = '0'
      }
      else if (buttonVal == "back") {
        var length = res.length
        if (length > 1) {
          res = res.substr(0, length - 1)
        }
        else {
          res = '0'
        }
      }
      else if (buttonVal == "div" || buttonVal == "mul" || buttonVal == "sub" || buttonVal == "add") {
        switch (buttonVal) {
          case "div":
            sign = '÷'
            break
          case "mul":
            sign = '×'
            break
          case "sub":
            sign = '-'
            break
          case "add":
            sign = '+'
            break
        }
        if (!isNaN(res.charAt(res.length - 1))) {
          res = res + sign
        }
      }
    }
    this.setData({
      result: res,
      buttonDot: newbuttonDot,
    })
  },
  equal: function (e) {
    var str = this.data.result
    var item = ''
    var strArray = []
    var temp = 0
    for (var i = 0; i <= str.length; i++) {
      var s = str.charAt(i)
      if ((s != '' && s >= '0' && s <= '9') || s == '.') {
        item = item + s
      }
      else {
        strArray[temp] = item
        temp++
        strArray[temp] = s
        temp++
        item = ''
      }
    }
    if (isNaN(strArray[strArray.length - 1])) {
      strArray.pop()
    }
    var num
    var res = strArray[0] * 1
    for (var i = 1; i <= strArray.length; i = i + 2) {
      num = strArray[i + 1]
      switch (strArray[i]) {
        case "-":
          res = res - num
          break
        case "+":
          res = Number(res) + Number(num)
          break
        case "×":
          res = res * num
          break
        case "÷":
          if (num != '0') {
            res = res / num
          }
          else {
            res = '∞'
            break
          }
          break
      }
    }
    this.setData({
      result: '=' + res,
    })
  }
})